package com.gistone.commis.service;


import com.gistone.commis.entity.Role;
import com.gistone.commis.entity.User;
import com.gistone.commis.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zoud on 2016/11/15.
 */

@Service
public class UserService implements UserDetailsService {
    @Autowired
    UserMapper userMapper;






    @Override
    public UserDetails loadUserByUsername(String username) throws BadCredentialsException {
        User user = userMapper.findUserByUserName(username);
        System.out.println("username"+user.getUserName()+"pwd:"+user.getUserPwd());
        if (user == null) {
            throw new BadCredentialsException("Username or password error!");
        }

        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        //用于添加用户的权限。只要把用户权限添加到authorities 就万事大吉。
        for(Role role:user.getRoles())
        {
            authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
            System.out.println(role.getRoleName());
        }
        return new org.springframework.security.core.userdetails.User(user.getUserName(),
                user.getUserPwd(), authorities);
    }






}
